<?php

namespace App\Http\Controllers\Common;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Services\sendTemplateSMS;
use App\Models\Sms_log;

class SmsController extends Controller
{
    const CODE_NOT_EXISTS = '2221';//验证码不存在
    const CODE_EXPIRED = '2222';//验证码过期,
    const CODE_ERROR = '2223';//验证马错误
    const CODE_OK = '0000';//验证码正确
    const SMS_TYPE_CODE = 'code';
    const SMS_TYPE_NOTIFY = 'notify';

    public function sendCode(Request $request)
    {
        $mobile = $request->mobile;
        $SMS = new sendTemplateSMS();
        $code = $this->getNonceNum();
        $ret = $SMS->sendTemplateSMS($mobile, array($code, '1分钟'), '204912');
        if ($ret['error'] == '0') {
            $data['mobile'] = $mobile;
            $data['type'] = 'code';
            $data['code'] = $code;
            $data['sms_id'] = $ret['smsMessageSid'];
            $data['response'] = json_encode($ret);
            $data['send_time'] = $ret['dateCreated'];
            $data['expire_time'] = date("Y-m-d H:i:s", (strtotime($ret['dateCreated']) + 1 * 60));
            $data['status'] = 1;
            $data['create_ip'] = $request->getClientIp();
            $data['create_time'] = date("Y-m-d H:i:s");
            $ret = Sms_log::create($data);
            if ($ret) {
                return [
                    'code' => '0000',
                    'message' => '发送成功'
                ];
            }
        } else if ($ret['error'] == '1') {
            return [
                'code' => '1111',
                'message' => '发送成功'
            ];
        }
    }

    public static function verifyCode($mobile, $code)
    {
        $smsLog = Sms_log::where('status', 1)
            ->where('type', static::SMS_TYPE_CODE)
            ->where('mobile', $mobile)
            ->orderBy('id', 'desc')
            ->first();
        if (count($smsLog) == 0 || empty($smsLog->code)) {
            return ['code' => static::CODE_NOT_EXISTS, 'message' => '验证码不存在'];
        }
        if ($smsLog->expire_time < date('Y-m-d H:i:s')) {
            return ['code' => static::CODE_EXPIRED, 'message' => '验证码已过期'];
        }
        if ($smsLog->code != $code) {
            return ['code' => static::CODE_ERROR, 'message' => '验证码错误'];
        }
        //验证通过后，让验证码过期掉
        $smsLog->expire_time = date('Y-m-d H:i:s');
        //$smsLog->save();
        return ['code' => static::CODE_OK, 'message' => '验证通过'];

    }

    private function getNonceNum($length = 6)
    {
        $chars = "0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
}
